﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using Newtonsoft.Json;

using tcm.entity;
using tcm.request;
using tcm.response;
using tcm.utils;

namespace tcm.Controller
{
    [ApiController]
    [Route("tcm/wechat")]
    public class WeChatController : GCCAPIControllerBase
    {
        public WeChatController(AbsGCCContext context) : base(context)
        {

        }

        [HttpGet("userInfo/{code}")]
        public async Task<DataResponse<WeChatUserRes>> GetUserInfo([FromRoute] string code)
        {
            var result = new WeChatUserRes();
            string msg = string.Empty;
            if (string.IsNullOrWhiteSpace(code))
                return SystemError<WeChatUserRes>("code不能为空");
            var help = new HttpHelper();
            try
            {
                StringBuilder str = new StringBuilder();

                var parameter = string.Format("appid={0}&secret={1}&code={2}&grant_type={3}", GlobalConstant.Appid, GlobalConstant.AppSecret, code, GlobalConstant.GrantType);
                _=str.Append(GlobalConstant.WeChatAccessTokenUrl+"?"+parameter);

                var response = help.GetAsync(url: str.ToString()).Result;
                if (response.IsSuccessStatusCode)
                {
                    var res = response.Content.ReadAsStringAsync().Result;
                    var tokenRes = JsonConvert.DeserializeObject<WeChatUserTokenRes>(res);
                    if (!string.IsNullOrWhiteSpace(tokenRes.access_token))
                    {
                        StringBuilder stringBuilder = new StringBuilder();

                        var parameterUser = string.Format("access_token={0}&openid={1}&lang=zh_CN", tokenRes.access_token, tokenRes.openid);
                        _=stringBuilder.Append(GlobalConstant.WeChatUserinfoUrl+"?"+parameterUser);

                        var userResponse = help.GetAsync(url: stringBuilder.ToString()).Result;
                        if (userResponse.IsSuccessStatusCode)
                        {
                            var userRes = userResponse.Content.ReadAsStringAsync().Result;
                            result = JsonConvert.DeserializeObject<WeChatUserRes>(userRes);
                            if (string.IsNullOrWhiteSpace(result.openid))
                                msg="接口返回异常"+ userRes;
                            result.accessToken=tokenRes.access_token;
                        }
                    }
                    else
                    {
                        msg="接口返回异常："+ res;
                    }
                }
            }
            catch (Exception exe)
            {
                msg="调用接口异常,异常信息："+exe.Message;
            }

            if (!string.IsNullOrWhiteSpace(msg))
                return SystemError<WeChatUserRes>(msg);
            return HandleData(result);
        }
    }
}
